package win.demonlegion.common;

import win.demonlegion.util.RandomUtil;

import java.io.Serializable;
import java.math.BigInteger;

/**
 * 协商密码实现
 */
public class DiffieHellmanKeyExchange implements Serializable {
    private static final long serialVersionUID = 3111270664649108637L;
    private static final int DEFAULT_PRIME_BIT_LENGTH = 100;
    private static final int DEFAULT_KEY_BIT_LENGTH = 10;
    private static final int MIN_ROOT_LIMIT = 100000;
    private static final int ROOT_RANGE = 1000000;

    private int root;
    private BigInteger prime;
    private BigInteger localPrivateKey;
    private BigInteger shareKey;

    public DiffieHellmanKeyExchange() {
        this(RandomUtil.getRandomDelay(ROOT_RANGE, MIN_ROOT_LIMIT));
    }

    public DiffieHellmanKeyExchange(int root) {
        this(root, RandomUtil.getRandomPrime(DEFAULT_PRIME_BIT_LENGTH));
    }

    public DiffieHellmanKeyExchange(int root, BigInteger prime) {
        this.root = root;
        this.prime = prime;
        localPrivateKey = RandomUtil.getRandomBigInteger(DEFAULT_KEY_BIT_LENGTH);
    }

    public BigInteger calculateLocalPublicKey() {
        BigInteger bigInteger = BigInteger.valueOf(root);
        return bigInteger.modPow(localPrivateKey, prime);
    }

    public BigInteger calculateShareKey(BigInteger otherPublicKey) {
        shareKey = otherPublicKey.modPow(localPrivateKey, prime);
        return shareKey;
    }

    public int getRoot() {
        return root;
    }

    public void setRoot(int root) {
        this.root = root;
    }

    public BigInteger getPrime() {
        return prime;
    }

    public void setPrime(BigInteger prime) {
        this.prime = prime;
    }
}
